/*Author: Rony Lahav (ID:043489889)*/

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashMap;


/**
 * This class handles a single TCP incoming session - after a connection was accepted, reads a GET message and sends the relevant file
 */
public class SingleTCPIncomingConnection implements Runnable{

	Socket s = null;
	long uniqueID;
	BufferedReader br;
	DataOutputStream dos;
	private HashMap<String,String> parsedMsg;
	
	public SingleTCPIncomingConnection(Socket soc, long uniqueID) {
		this.uniqueID = uniqueID;
		this.s=soc;
	}
	
	public void run(){
		try{
			TCPHandleConnection();
		}
		catch(Exception e){
		}
		finally{
			try {
				if (br!=null)
					br.close();
				if (dos!=null)
					dos.close();
			} catch (IOException e) {}
			final_project.removeThreadFromLivingList(uniqueID);
		}
	}
	
	/**
	 * This method reads a GET message from an accepted connection and sends the relevant file
	 */
	public void TCPHandleConnection() {
		try {
			if (!final_project.isShutDown()){
				br = new BufferedReader(new InputStreamReader(s.getInputStream()));
				dos = new DataOutputStream(s.getOutputStream());
				String msg=readMessage();
				parsedMsg=MessageCenter.getInstance().parseValidMessage(msg, null, s.getInetAddress().getHostAddress());
				if (parsedMsg!=null){	//no error
					String fileName = parsedMsg.get(MessageCenter.VAR_FILE);
					dos.write(final_project.loadedFiles.get(fileName));
				}
			}
		}
		catch (SocketTimeoutException e1){}
		catch (IOException e2){}
	}

	public long getUniqueID(){
		return uniqueID;
	}
	
	//reads a GET message
	private String readMessage() throws IOException{
		String msg="";
		do{
			 msg += br.readLine() + MessageCenter.newline;
		}while(!msg.contains("FILE") && !final_project.isShutDown());
		return msg;
	}
}
